<template>
  <el-drawer
    title=""
    :visible.sync="dialogVisible"
    :with-header="false"
    :modal="false"
    :wrapper-closable="false"
    size="95%"
    :modal-append-to-body="false"
  >
    <div class="mind-edit" :class="readonly ? 'node-readonly' : ''">
      <span class="closeDrawer" @click="cancel()"><i class="el-icon-arrow-right" /></span>
      <div class="module-mind">
        <div class="area-header">
          <span class="area-header-title">{{ $t('产品/服务目录') }}</span>
        </div>
        <div class="directorySpan">
          <span v-for="(v, i) in directoryList" :key="v.data.uid">
            <div v-if="i>0" class="arrow-line" />
            <span :class="directoryList.length - 1 === i ? 'link-type' : ''">{{ v.data.text }}</span>
          </span>
        </div>
      </div>
      <div class="module-mind">
        <!-- 附件 -->
        <FileTable :list.sync="fileList" data-type="mind" :btn-show="!otherBtnHide" @handleChange="fileHandleChange" />
      </div>
      <div v-loading="loading" class="module-mind">
        <div class="area-header">
          <span class="area-header-title">{{ $t('项目信息') }}</span>
          <el-button
            v-if="!readonly"
            type="primary"
            icon="el-icon-plus"
            size="mini"
            plain
            @click="addHandle"
          >{{ $t("新增") }}</el-button>
        </div>
        <ul class="dealUl">
          <el-form ref="queryForm" :inline="true" @submit.native.prevent>
            <el-form-item :label="$t('项目名称')" prop="selectedDealsSearchVal">
              <el-input
                v-model="selectedDealsSearchVal"
                :placeholder="$t('项目名称')"
                clearable
                size="small"
                @clear="resetQuery"
                @keyup.enter.native="matchedOptions"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="dealQueryHandle">{{ $t('搜索') }}</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('重置') }}</el-button>
            </el-form-item>
          </el-form>
          <li v-for="(row, index) in selectDealsData" :key="row.id">
            <h3><router-link target="_blank" :to="{path:'/deal/home/dealBaseHome',query:{id:row.id,companyId:row.companyId}}" class="">{{ row.dealName }}</router-link><i class="el-icon-delete" @click="delHandle(index, row)" /></h3>
            <div class="flex-row">
              <div>
                <span>{{ $t('负责人') }}: </span>
                <span>{{ row.personChargeName }}</span>
              </div>
              <div>
                <span>{{ $t('项目阶段') }}: </span>
                <span>{{ dealStatusFormat(row) || '-' }}</span>
              </div>
              <div>
                <span>{{ $t('行业') }}: </span>
                <span>{{ industryFocusFormat(row) || '-' }}</span>
              </div>
            </div>
            <div class="bottom link-type" @click="onTrack(row.id)">{{ $t('项目跟踪') }}</div>
          </li>
          <el-pagination
            v-show="selectedDeals.length>0"
            :current-page="currentPage"
            :page-size="pagesize"
            layout="total, prev, pager, next"
            :total="selectedDeals.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </ul>

        <!-- 新增项目 -->
        <el-dialog v-el-drag-dialog :title="$t('新增项目')" :visible.sync="formOpen" width="60%" :close-on-click-modal="false" :lock-scroll="false" destroy-on-close custom-class="" append-to-body>
          <div v-if="formOpen">
            <el-form
              ref="queryFormAdd"
              :model="queryParamsAdd"
              :inline="true"
            >
              <el-form-item :label="$t('项目名称')" prop="dealName">
                <el-input v-model="queryParamsAdd.dealName" :placeholder="$t('项目名称')" clearable size="small" @keyup.enter.native="queryHandleAdd" />
              </el-form-item>
              <el-form-item :label="$t('负责人')" prop="personCharge">
                <userSelect
                  v-model="queryParamsAdd.personCharge"
                  size="small"
                  :placeholder="$t('负责人')"
                  clearable
                  @keyup.enter.native="queryParamsAdd"
                />
              </el-form-item>
              <el-form-item :label="$t('聚焦行业')" prop="industryFocus">
                <el-select v-model="queryParamsAdd.industryFocus" :placeholder="$t('聚焦行业')" clearable>
                  <el-option
                    v-for="dict in industryFocusOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandleAdd">{{ $t("搜索") }}</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQueryAdd">{{ $t("重置") }}</el-button>
              </el-form-item>
            </el-form>
            <el-table ref="table" v-loading="loadingAdd" border :data="allDealList" row-key="id" height="40vh" @selection-change="handleSelectionChange">
              <el-table-column type="selection" :reserve-selection="true" width="55" align="center" />
              <el-table-column :label="$t('序号')" type="index" align="center" width="50" />
              <el-table-column :label="$t('项目名称')" prop="dealName" :show-overflow-tooltip="true" />
              <el-table-column :label="$t('负责人')" align="center" prop="personChargeName" width="140" />
              <el-table-column :label="$t('项目状态')" align="center" prop="dealStatus" :formatter="dealStatusFormat" width="120" />
              <el-table-column :label="$t('聚焦行业')" align="center" prop="industryFocus" :formatter="industryFocusFormat" width="120" />
              <!-- <el-table-column :label="$t('行业')" prop="industry" align="center" show-overflow-tooltip /> -->
            </el-table>
            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParamsAdd.pageNum"
              :limit.sync="queryParamsAdd.pageSize"
              @pagination="getDealList"
            />
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="handleCancel">{{ $t('取消') }}</el-button>
            <el-button v-if="!readonly" type="primary" @click="handleSubmit">{{ $t('确定') }}</el-button>
          </span>
        </el-dialog>
        <!-- 跟踪 -->
        <el-dialog v-el-drag-dialog :title="$t('项目跟踪')" :visible.sync="trackOpen" width="60%" :close-on-click-modal="false" :lock-scroll="false" destroy-on-close custom-class="" append-to-body>
          <dealReportView :deal-id-list="dealTracktId" :readonly="readonly" />
        </el-dialog>
      </div>
      <!-- <span class=" footer-mind">
        <el-button @click="cancel">{{ $t('dialog.cancel') }}</el-button>
        <el-button v-if="!readonly" type="primary" @click="confirm">{{ $t('dialog.confirm') }}</el-button>
      </span> -->
    </div>
  </el-drawer>
</template>

<script>
import { getDealListLite } from '@/api/base/deal/dealBase'
import dealReportView from './dealReportView'
export default {
  name: 'NodeDeal',
  components: {
    dealReportView
  },
  props: {
    readonly: {
      type: Boolean,
      false: () => false
    },
    mindMapData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      // 总条数
      total: 0,
      dialogVisible: false,
      formOpen: false,
      tagArr: [],
      tag: '',
      activeNodes: [],
      max: 5,
      loading: false,
      loadingAdd: false,
      actPhaseOptions: [],
      dealNameFilters: [],
      dealStatusFilters: [],
      industryFocusFilters: [],
      allDealList: [
      ],
      selectedDeals: [],
      queryParams: {
        pageNum: 1,
        pageSize: 20
      },
      queryParamsAdd: {
        dealName: undefined,
        pageNum: 1,
        pageSize: 20,
        personCharge: undefined
      },
      queryParams1: {},
      cacheDeal: [],
      iconList: [],
      // 项目状态字典
      dealStatusOptions: [],
      // 聚焦行业字典
      industryFocusOptions: [],
      activeTab: '1',
      dealIdList: [],
      otherBtnHide: false,
      fileList: [],
      directoryList: [],
      selectedDealsSearchVal: '',
      trackOpen: false,
      dealTracktId: [],
      pagesize: 5,
      currentPage: 1,
      selectDealsData: []
    }
  },
  watch: {
    selectedDeals: {
      handler(val) {
        if (val) {
          this.dealNameFilters = []
          if (this.selectedDeals.length > 0) {
            this.dealIdList = this.selectedDeals.map(v => v.id)
          } else {
            this.dealIdList = []
          }
        } else {
          this.dealIdList = []
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.$bus.$on('node_active', this.handleNodeActive)
    this.$bus.$on('node_click', this.handleNodeClick)
  },
  beforeDestroy() {
    this.$bus.$off('node_active', this.handleNodeActive)
    this.$bus.$off('node_click', this.handleNodeClick)
  },
  mounted() {
    this.$bus.$on('showNodeDeal', () => {
      // this.$bus.$emit('startTextEdit')
      // this.activeTab = '1'
      this.dialogVisible = true
    })
    this.getDicts('deal_status').then(response => {
        this.dealStatusOptions = response.data
    })
    this.getDicts('deal_industry_focus').then(response => {
      this.industryFocusOptions = response.data
    })
    // 查询项目
    // this.getDealList()
  },
  methods: {
    fileHandleChange(data) {
      // console.log(data, 999)
      const _key = 'other2_file'
      const _index = this.iconList.findIndex(item => { return item === _key })
      if (data.length > 0) {
        if (_index === -1) { this.iconList.push(_key) }
      } else {
        if (_index !== -1) { this.iconList.splice(_index, 1) }
      }

      this.activeNodes.forEach(node => {
        node.setIcon([...this.iconList])
        node.nodeData.data.fileList = data
      })
      this.activeNodes.forEach(node => {
        node.setIcon([...this.iconList])
      })
    },
    handleSizeChange(val) {
      this.pagesize = val
      this.selectDealsData = this.selectedDeals.slice(this.pagesize * (this.currentPage - 1), this.pagesize * this.currentPage)
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.selectDealsData = this.selectedDeals.slice(this.pagesize * (this.currentPage - 1), this.pagesize * this.currentPage)
    },
    dealQueryHandle() {
      this.matchedOptions()
    },
    resetQuery() {
      this.selectedDealsSearchVal = ''
      this.currentPage = 1
      this.matchedOptions()
    },
    matchedOptions() {
      var options = JSON.parse(JSON.stringify(this.cacheDeal))
      if (this.selectedDealsSearchVal !== '') {
        this.selectedDeals = options.filter(v => v.dealName.includes(this.selectedDealsSearchVal))
      } else {
        this.selectedDeals = options
      }
      this.selectDealsData = this.selectedDeals.slice(this.pagesize * (this.currentPage - 1), this.pagesize * this.currentPage)
    },
    onTrack(id) {
      this.trackOpen = true
      this.dealTracktId = [id]
    },
    async handleNodeActive(...args) {
      this.activeNodes = args[1] || null
      this.selectedDeals = []
      if (this.activeNodes.length > 0) {
        console.log('监听节点', this.activeNodes)
        const firstNode = this.activeNodes[0]
        this.iconList = firstNode.getData('icon') || []
        var deals = firstNode.getData('deals') || []
        this.fileList = firstNode.getData('fileList') || []
        // 根据id的集合查询最新的信息
        var dealIdList = deals.map(v => v.id)
        await this.getDealListByDealIds(dealIdList)
        for (let i = 0; i < this.cacheDeal.length; i++) {
          this.$set(this.cacheDeal[i], 'selected', true)
        }
        if (this.selectedDeals.length > 0) {
          this.dealIdList = this.selectedDeals.map(v => v.id)
        }
        // console.log(this.mindMapData, 111)
        var _data = [this.mindMapData.root]
        this.directoryList = this.getAllParentArr(_data, firstNode.uid) || []
        this.directoryList = this.directoryList.reverse()
      } else {
        this.iconList = []
        this.selectedDeals = []
        this.cacheDeal = []
        this.dealIdList = []
        this.fileList = []
      }
    },
    async handleNodeClick(...args) {
      if (this.readonly) {
        console.log('只读模式下点击节点........', args)
        var activeNodes = args[0]
        this.fileList = activeNodes.nodeData.data.fileList || []
       // this.selectedDeals = activeNodes.nodeData.data.deals || []
        var deals = activeNodes.nodeData.data.deals || []
        // 根据id的集合查询最新的信息
        var dealIdList = deals.map(v => v.id)
        await this.getDealListByDealIds(dealIdList)

        // console.log(this.mindMapData, 111)
        var _data = [this.mindMapData.root]
        this.directoryList = this.getAllParentArr(_data, activeNodes.nodeData.data.uid) || []
        this.directoryList = this.directoryList.reverse()
      }
    },
    getDealList() {
      // console.log(this.cacheDeal, 'this.cacheDeal')
      this.loadingAdd = true
      getDealListLite(this.queryParamsAdd).then(response => {
        this.allDealList = response.rows
        this.total = response.total
        this.loadingAdd = false
        for (let i = 0; i < this.allDealList.length; i++) {
          var row = this.cacheDeal.find(v => v.id === this.allDealList[i].id)
          if (row) {
            this.$nextTick(() => {
              this.$refs.table.toggleRowSelection(this.allDealList[i], true)
            })
          }
        }
      })
    },
    getDealListByDealIds(ids) {
      this.selectedDealsSearchVal = ''
      this.currentPage = 1
      if (ids && ids.length > 0) {
        this.loadingAdd = true
        var queryData = Object.assign({}, this.queryParamsAdd)
        queryData.idsStr = ids.join(',')
        getDealListLite(queryData).then(response => {
          this.selectedDeals = response.rows
          this.cacheDeal = JSON.parse(JSON.stringify(response.rows))
          this.selectDealsData = this.selectedDeals.slice(this.pagesize * (this.currentPage - 1), this.pagesize * this.currentPage)
        })
      } else {
        this.selectedDeals = []
        this.cacheDeal = []
        this.selectDealsData = []
      }
    },
    formatText(htmlStr) {
      if (!htmlStr) return ''
      return htmlStr.replace(/<\/?.+?>/g, '').replace(/ /g, '').replace(/&nbsp;/ig, '')
    },
    cancel() {
      // this.activeTab = '1'
      this.dialogVisible = false
      this.$bus.$emit('endTextEdit')
    },
    queryHandle() {
      this.queryParams.pageNum = 1
      // this.getDealList()
    },
    queryHandleAdd() {
      this.queryParamsAdd.pageNum = 1
      this.getDealList()
    },
    resetQueryAdd() {
      this.resetForm('queryFormAdd')
      this.queryParamsAdd.dealName = ''
      this.queryHandleAdd()
    },
    handleSelectionChange(val) {
      const selectArr = val
      for (let i = 0; i < selectArr.length; i++) {
        this.$set(selectArr[i], 'selected', true)
      }
      const selectList = []
      this.allDealList.forEach((item) => {
        this.$set(item, 'selected', false)
        selectArr.forEach((v) => {
          if (v.id === item.id) {
            this.$set(item, 'selected', true)
          }
        })
        selectList.push(item)
      })

      selectList.forEach((item) => {
        var index = this.cacheDeal.findIndex(v => v.id === item.id && !item.selected)
        // console.log(index)
        if (index !== -1) {
          this.cacheDeal.splice(index, 1)
        }

        if (item.selected) {
          this.cacheDeal.push(item)
        }
      })
      const res = new Map()
      this.cacheDeal = this.cacheDeal.filter((v) => !res.has(v.id) && res.set(v.id, 1))
    },
    delHandle(index) {
      this.selectedDeals.splice(index, 1)
      this.cacheDeal.splice(index, 1)
      if (this.selectedDeals.length > 0) {
        this.dealIdList = this.selectedDeals.map(v => v.id)
      }

      this.saveDeals()
    },
    addHandle() {
      this.getDealList()
      this.formOpen = true
    },
    handleCancel() {
      this.$refs.table.clearSelection()
      this.formOpen = false
      this.cacheDeal = JSON.parse(JSON.stringify(this.selectedDeals))
      for (let i = 0; i < this.cacheDeal.length; i++) {
        this.$set(this.cacheDeal[i], 'selected', true)
      }
    },
    handleSubmit() {
      this.selectedDeals = JSON.parse(JSON.stringify(this.cacheDeal))
      if (this.selectedDeals.length > 0) {
        this.dealIdList = this.selectedDeals.map(v => v.id)
      }
      this.formOpen = false
      this.selectDealsData = this.selectedDeals.slice(this.pagesize * (this.currentPage - 1), this.pagesize * this.currentPage)
      this.saveDeals()
    },
    saveDeals() {
      const key = 'other1_deal'
      const index = this.iconList.findIndex(item => { return item === key })
      if (this.selectedDeals.length > 0) {
        if (index === -1) { this.iconList.push(key) }
      } else {
        if (index !== -1) { this.iconList.splice(index, 1) }
      }
      this.activeNodes.forEach(node => {
        node.setIcon([...this.iconList])
        node.nodeData.data.deals = this.selectedDeals
        node.nodeData.data.newNote = node.nodeData.data.note
      })

      this.activeNodes.forEach(node => {
        node.setIcon([...this.iconList])
      })
    },
    // confirm() {
    //   const _key = 'other2_file'
    //   const _index = this.iconList.findIndex(item => { return item === _key })
    //   if (this.fileList.length > 0) {
    //     if (_index === -1) { this.iconList.push(_key) }
    //   } else {
    //     if (_index !== -1) { this.iconList.splice(_index, 1) }
    //   }

    //   this.activeNodes.forEach(node => {
    //     node.setIcon([...this.iconList])
    //     node.nodeData.data.fileList = this.fileList
    //   })
    //   this.activeNodes.forEach(node => {
    //     node.setIcon([...this.iconList])
    //   })
    //   this.cancel()
    // },
    // 项目状态字典翻译
    dealStatusFormat(row) {
      return this.selectDictLabel(this.dealStatusOptions, row.dealStatus)
    },
    // 聚焦行业 字典deal_industry_focus字典翻译
    industryFocusFormat(row) {
      return this.selectDictLabel(this.industryFocusOptions, row.industryFocus)
    },
    // filterHandler(value, row, column) {
    //   const property = column['dealName']
    //   return row[property] === value
    // }
    filterHandler(value, row) {
      return row.dealName === value
    },
    filterPersonChargeName(value, row) {
      return row.personChargeName === value
    },
    filterDealStatus(value, row) {
      return row.dealStatus === value
    },
    filterIndustry(value, row) {
      return row.industryFocus === value
    },
    getAllParentArr(list, uid) {
      for (const i in list) {
        if (list[i].data.uid === uid) {
          // 查询到返回该数组对象
          return [list[i]]
        }
        if (list[i].children) {
          const node = this.getAllParentArr(list[i].children, uid)
          if (node !== undefined) {
            // 查询到把父节点连起来
            return node.concat(list[i])
          }
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.mindNodeDialog {
  /deep/.el-form {
    display: flex;
    .el-form-item {
      display: inline-flex;
      .el-form-item__label {
          white-space: nowrap;
      }
    }
  }
}
.text{
  /* autoprefixer: off */
  display:-webkit-box;
  -webkit-line-clamp: 2;
  overflow: hidden;
  -webkit-box-orient: vertical;
  text-overflow: ellipsis;
  /* autoprefixer: on */
  max-height: 50px
}
.msgCount{
  position: relative;
  display: inline-block;
  float: right;
  padding: 0 3px 0 0;
  margin-left: 10px;
  .icon{
    background-color: #f56c6c;
    border-radius: 10px;
    color: #fff;
    display: inline-block;
    font-size: 12px;
    height: 18px;
    line-height: 18px;
    padding: 0 6px;
    text-align: center;
    white-space: nowrap;
    position: absolute;
    right: -8px;
    top: -3px;
    zoom: 0.9;
  }
}
/deep/.node-readonly{
  .tol, .el-icon-delete, .el-icon-more{
    display: none;
  }
}

.mind-edit{
  padding: 20px;
  padding-left: 30px;
  position: relative;
  height: 100vh;
  overflow: auto;
  .module-mind{
    // border: 1px solid #d8d8d8;
    // border-radius: 4px;
    // padding: 10px;
    margin-bottom: 15px;
    /deep/.area-header{
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 0!important;
      margin-bottom: 10px;
      .area-header-title{
        font-size: 16px;
      }
    }
  }
}
.dealUl{
  margin-top: 15px;
  // max-height: 700px;
  // overflow: auto;
  // margin-right: -10px;
  // padding-right: 15px;
  li{
    margin-bottom: 20px;
    h3{
      font-size: 14px;
      font-weight: bold;
      color: #555;
      margin: 0;
      margin-bottom: 8px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      i{
        cursor: pointer;
      }
    }
    .bottom{
      font-size: 14px;
      text-decoration: underline;
      margin-top: 8px;
    }
    .flex-row{
      display: flex;
      align-items: center;
      font-size: 14px;
      color: #787878;
      >div{
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        flex: 1;
      }
    }
  }
}
.footer-mind{
  position: fixed;
  right: 0;
  bottom: 0;
  background: #fff;
  width: calc(40% - 35px);
  padding: 10px 20px 20px;
}

.arrow-line {
    position: relative;
    width: 35px;
    height: 1px;
    display: inline-block;
    background-color: #7b7b7b;
    position: relative;
    top: -4px;
    &::before, &::after{
      content: "";
      position: absolute;
      height: 8px;
      width: 1px;
      background: #7b7b7b;
      right: 3px;
      bottom: -1px;
      transform: rotate(-50deg);
    }
    &::after{
      top: -1px;
      bottom: unset;
      transform: rotate(50deg);
    }
}
.directorySpan{
  line-height: 20px;
  span{
    font-size: 14px;
    cursor: auto;
  }
}
.noMore{
  font-size: 14px;
  color: #999999;
  text-align: center;
  margin: 50px auto 0;
}
.closeDrawer{
  position: absolute;
  top: calc(50% - 60px);
  left: 0;
  height: 120px;
  width: 15px;
  background: #e7e7e7;
  cursor: pointer;
  border-radius: 0 10px 10px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #868686;
}

</style>
